<template>
  <div class="orders-dashboard">
    <h1 class="page-title">订单趋势</h1>
    
    <!-- 订单总览统计 -->
    <el-row :gutter="20" class="kpi-section">
      <el-col :span="6" v-for="(item, index) in kpiData" :key="index">
        <el-card class="kpi-card" :class="item.type">
          <div class="kpi-icon">
            <el-icon><component :is="item.icon" /></el-icon>
          </div>
          <div class="kpi-content">
            <div class="kpi-title">{{ item.title }}</div>
            <div class="kpi-value">{{ item.format(animatedValues[index]) }}</div>
            <div class="kpi-change" :class="item.trend">
              <el-icon><component :is="item.trend === 'up' ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
              {{ item.change }}
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 订单趋势图 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>订单趋势</h3>
              <div class="chart-controls">
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  size="small"
                />
                <el-radio-group v-model="trendMetric" size="small" style="margin-left: 15px;">
                  <el-radio-button label="count">订单数</el-radio-button>
                  <el-radio-button label="amount">订单金额</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart" id="order-trend-chart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 订单分析区域 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 订单状态分布 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>订单状态分布</h3>
            </div>
          </template>
          <div class="chart" id="order-status-chart"></div>
        </el-card>
      </el-col>
      
      <!-- 订单来源分布 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>订单来源分布</h3>
            </div>
          </template>
          <div class="chart" id="order-source-chart"></div>
        </el-card>
      </el-col>
      
      <!-- 支付方式分布 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>支付方式分布</h3>
            </div>
          </template>
          <div class="chart" id="payment-method-chart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 热销产品和地区分布 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 热销产品排行 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>热销产品排行</h3>
              <div class="chart-controls">
                <el-select v-model="productSortBy" size="small" placeholder="排序方式">
                  <el-option label="按销量" value="volume" />
                  <el-option label="按金额" value="amount" />
                </el-select>
              </div>
            </div>
          </template>
          <div class="chart" id="hot-products-chart"></div>
        </el-card>
      </el-col>
      
      <!-- 订单地区分布 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>订单地区分布</h3>
            </div>
          </template>
          <div class="chart" id="order-region-chart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 客户价值矩阵 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>客户价值矩阵</h3>
              <div class="chart-controls">
                <el-tooltip content="基于购买频率和平均消费金额的客户分布" placement="top">
                  <el-icon class="info-icon"><InfoFilled /></el-icon>
                </el-tooltip>
              </div>
            </div>
          </template>
          <div class="chart" id="customer-matrix-chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
import { ShoppingCart, Money, PriceTag, RefreshRight, InfoFilled } from '@element-plus/icons-vue'

// KPI数据
const kpiData = [
  {
    title: '总订单数',
    value: '85,324',
    numericValue: 85324,
    format: (val: number) => val.toLocaleString(),
    change: '15.2% 较上月',
    trend: 'up',
    icon: 'ShoppingCart',
    type: 'primary'
  },
  {
    title: '订单总额',
    value: '￥4,382,145',
    numericValue: 4382145,
    format: (val: number) => `￥${val.toLocaleString()}`,
    change: '12.7% 较上月',
    trend: 'up',
    icon: 'Money',
    type: 'success'
  },
  {
    title: '平均客单价',
    value: '￥513.57',
    numericValue: 513.57,
    format: (val: number) => `￥${val.toFixed(2)}`,
    change: '2.1% 较上月',
    trend: 'down',
    icon: 'PriceTag',
    type: 'warning'
  },
  {
    title: '退单率',
    value: '2.8%',
    numericValue: 2.8,
    format: (val: number) => `${val.toFixed(1)}%`,
    change: '0.3% 较上月',
    trend: 'down',
    icon: 'RefreshRight',
    type: 'danger'
  }
]

// 动画显示的值
const animatedValues = ref(kpiData.map(() => 0))

// 动画效果函数
const animateValues = () => {
  // 为每个卡片创建动画
  kpiData.forEach((data, index) => {
    const targetValue = data.numericValue
    const duration = 2000 // 动画持续2秒
    const startTime = Date.now()
    
    const animate = () => {
      const currentTime = Date.now()
      const elapsed = currentTime - startTime
      
      if (elapsed < duration) {
        // 使用easeOutExpo缓动函数让动画更自然
        const progress = 1 - Math.pow(1 - elapsed / duration, 3)
        animatedValues.value[index] = targetValue * progress
        requestAnimationFrame(animate)
      } else {
        animatedValues.value[index] = targetValue
      }
    }
    
    animate()
  })
}

// 控制变量
const dateRange = ref([
  new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000),
  new Date()
])
const trendMetric = ref('count')
const productSortBy = ref('volume')

// 图表实例
let trendChart: echarts.ECharts | null = null
let statusChart: echarts.ECharts | null = null
let sourceChart: echarts.ECharts | null = null
let paymentChart: echarts.ECharts | null = null
let productsChart: echarts.ECharts | null = null
let regionChart: echarts.ECharts | null = null
let customerMatrixChart: echarts.ECharts | null = null

// 初始化订单趋势图
const initTrendChart = () => {
  if (!trendChart) {
    trendChart = echarts.init(document.getElementById('order-trend-chart') as HTMLElement)
  }
  
  const now = new Date()
  const dates = []
  const data1 = []
  const data2 = []
  
  for (let i = 0; i < 30; i++) {
    const date = new Date(now.getTime() - (29 - i) * 24 * 60 * 60 * 1000)
    dates.push([date.getFullYear(), date.getMonth() + 1, date.getDate()].join('/'))
    data1.push(Math.round(Math.random() * 200 + 100))
    data2.push(Math.round(Math.random() * 50000 + 10000))
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['订单数', '订单金额']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: [
      {
        type: 'value',
        name: '订单数',
        position: 'left',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#5470C6'
          }
        },
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '订单金额',
        position: 'right',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#91CC75'
          }
        },
        axisLabel: {
          formatter: '{value} 元'
        }
      }
    ],
    series: [
      {
        name: '订单数',
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#5470C6'
        },
        yAxisIndex: 0,
        data: data1
      },
      {
        name: '订单金额',
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#91CC75'
        },
        yAxisIndex: 1,
        data: data2
      }
    ]
  }
  
  trendChart.setOption(option)
}

// 初始化订单状态分布图
const initStatusChart = () => {
  if (!statusChart) {
    statusChart = echarts.init(document.getElementById('order-status-chart') as HTMLElement)
  }
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      bottom: '5%',
      left: 'center',
      data: ['已完成', '处理中', '待付款', '已取消', '已退款']
    },
    series: [
      {
        name: '订单状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 1048, name: '已完成' },
          { value: 735, name: '处理中' },
          { value: 580, name: '待付款' },
          { value: 300, name: '已取消' },
          { value: 184, name: '已退款' }
        ]
      }
    ]
  }
  
  statusChart.setOption(option)
}

// 初始化订单来源分布图
const initSourceChart = () => {
  if (!sourceChart) {
    sourceChart = echarts.init(document.getElementById('order-source-chart') as HTMLElement)
  }
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      bottom: '5%',
      left: 'center'
    },
    series: [
      {
        name: '订单来源',
        type: 'pie',
        radius: '70%',
        data: [
          { value: 1048, name: '官方网站' },
          { value: 735, name: '移动应用' },
          { value: 580, name: '第三方平台' },
          { value: 300, name: '线下门店' },
          { value: 234, name: '电话订购' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  sourceChart.setOption(option)
}

// 初始化支付方式分布图
const initPaymentChart = () => {
  if (!paymentChart) {
    paymentChart = echarts.init(document.getElementById('payment-method-chart') as HTMLElement)
  }
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      bottom: '5%',
      left: 'center'
    },
    series: [
      {
        name: '支付方式',
        type: 'pie',
        radius: '70%',
        data: [
          { value: 1048, name: '支付宝' },
          { value: 735, name: '微信支付' },
          { value: 580, name: '银行卡' },
          { value: 300, name: '企业账户' },
          { value: 100, name: '其他' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  paymentChart.setOption(option)
}

// 初始化热销产品排行图
const initProductsChart = () => {
  if (!productsChart) {
    productsChart = echarts.init(document.getElementById('hot-products-chart') as HTMLElement)
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: productSortBy.value === 'volume' ? '销量' : '销售额'
    },
    yAxis: {
      type: 'category',
      data: ['智能手机', '笔记本电脑', '平板电脑', '智能手表', '无线耳机', '智能音箱', '相机', '游戏主机', '路由器', '智能家电'],
      axisLabel: {
        formatter: (value: string) => {
          if (value.length > 10) {
            return value.substring(0, 10) + '...'
          }
          return value
        }
      }
    },
    series: [
      {
        name: productSortBy.value === 'volume' ? '销量' : '销售额',
        type: 'bar',
        data: productSortBy.value === 'volume' 
          ? [1200, 980, 850, 720, 650, 590, 520, 470, 430, 380]
          : [980000, 820000, 650000, 450000, 380000, 320000, 280000, 240000, 210000, 180000]
      }
    ]
  }
  
  productsChart.setOption(option)
}

// 初始化订单地区分布图
const initRegionChart = () => {
  if (!regionChart) {
    regionChart = echarts.init(document.getElementById('order-region-chart') as HTMLElement)
  }
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    visualMap: {
      min: 0,
      max: 2000,
      inRange: {
        color: ['#e0f5ff', '#409EFF']
      },
      text: ['高', '低'],
      calculable: true
    },
    series: [
      {
        name: '订单量',
        type: 'map',
        map: 'china',
        label: {
          show: true
        },
        data: [
          { name: '北京', value: 1500 },
          { name: '上海', value: 2000 },
          { name: '广东', value: 1800 },
          { name: '江苏', value: 1300 },
          { name: '浙江', value: 1200 },
          { name: '四川', value: 1100 },
          { name: '湖北', value: 900 },
          { name: '河南', value: 800 },
          { name: '福建', value: 750 },
          { name: '山东', value: 720 },
          { name: '辽宁', value: 650 },
          { name: '安徽', value: 620 },
          { name: '湖南', value: 600 },
          { name: '陕西', value: 550 },
          { name: '河北', value: 520 },
          { name: '重庆', value: 500 },
          { name: '云南', value: 450 },
          { name: '黑龙江', value: 400 },
          { name: '山西', value: 380 },
          { name: '江西', value: 350 },
          { name: '贵州', value: 320 },
          { name: '吉林', value: 300 },
          { name: '广西', value: 280 },
          { name: '天津', value: 260 },
          { name: '内蒙古', value: 240 },
          { name: '新疆', value: 220 },
          { name: '甘肃', value: 200 },
          { name: '宁夏', value: 180 },
          { name: '海南', value: 160 },
          { name: '青海', value: 140 },
          { name: '西藏', value: 120 }
        ]
      }
    ]
  }
  
  regionChart.setOption(option)
}

// 初始化客户价值矩阵图
const initCustomerMatrixChart = () => {
  if (!customerMatrixChart) {
    customerMatrixChart = echarts.init(document.getElementById('customer-matrix-chart') as HTMLElement)
  }
  
  // 生成随机数据
  const data = []
  for (let i = 0; i < 100; i++) {
    data.push([
      Math.round(Math.random() * 10),                      // 购买频率
      Math.round(Math.random() * 1000) + 100,              // 平均消费
      Math.round(Math.random() * 100) + 10,                // 客户数量（气泡大小）
      ['低频低值', '低频高值', '高频低值', '高频高值'][Math.floor(Math.random() * 4)]  // 客户类型
    ])
  }
  
  const option = {
    title: {
      text: '客户价值矩阵分析',
      subtext: '基于购买频率和平均消费金额',
      left: 'center'
    },
    tooltip: {
      formatter: function (param: any) {
        return '客户群体: ' + param.data[3] + '<br/>' +
          '购买频率: ' + param.data[0] + ' 次/月<br/>' +
          '平均消费: ￥' + param.data[1] + '<br/>' +
          '客户数量: ' + param.data[2]
      }
    },
    xAxis: {
      type: 'value',
      name: '购买频率（次/月）',
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      },
      splitNumber: 10,
      min: 0,
      max: 10
    },
    yAxis: {
      type: 'value',
      name: '平均消费金额（元）',
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      },
      min: 0
    },
    visualMap: [
      {
        show: false,
        dimension: 3,
        categories: ['低频低值', '低频高值', '高频低值', '高频高值'],
        inRange: {
          color: ['#C23531', '#61A0A8', '#D48265', '#91C7AE']
        }
      }
    ],
    series: [
      {
        name: '客户价值',
        type: 'scatter',
        symbolSize: function (data: any) {
          return Math.sqrt(data[2]) * 3
        },
        encode: {
          x: 0,
          y: 1,
          tooltip: [0, 1, 2, 3]
        },
        data: data,
        markLine: {
          symbol: ['none', 'none'],
          label: {show: false},
          lineStyle: {
            type: 'solid'
          },
          data: [
            {xAxis: 5},
            {yAxis: 500}
          ]
        }
      }
    ]
  }
  
  customerMatrixChart.setOption(option)
}

// 自适应图表大小
const handleResize = () => {
  trendChart?.resize()
  statusChart?.resize()
  sourceChart?.resize()
  paymentChart?.resize()
  productsChart?.resize()
  regionChart?.resize()
  customerMatrixChart?.resize()
}

// 监听产品排序方式变化
watch(productSortBy, () => {
  initProductsChart()
})

// 监听筛选条件变化
watch(dateRange, () => {
  initTrendChart()
})

// 在组件挂载后初始化图表
onMounted(() => {
  // 动态加载中国地图数据
  echarts.registerMap('china', {
    type: 'FeatureCollection',
    features: []
  })
  
  // 初始化所有图表
  initTrendChart()
  initStatusChart()
  initSourceChart()
  initPaymentChart()
  initProductsChart()
  initRegionChart()
  initCustomerMatrixChart()
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
  
  // 启动数值动画
  animateValues()
})

// 在组件卸载前销毁图表实例
onBeforeUnmount(() => {
  if (trendChart) {
    trendChart.dispose()
    trendChart = null
  }
  if (statusChart) {
    statusChart.dispose()
    statusChart = null
  }
  if (sourceChart) {
    sourceChart.dispose()
    sourceChart = null
  }
  if (paymentChart) {
    paymentChart.dispose()
    paymentChart = null
  }
  if (productsChart) {
    productsChart.dispose()
    productsChart = null
  }
  if (regionChart) {
    regionChart.dispose()
    regionChart = null
  }
  if (customerMatrixChart) {
    customerMatrixChart.dispose()
    customerMatrixChart = null
  }
  
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.orders-dashboard {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #303133;
}

/* KPI卡片样式 */
.kpi-card {
  /* height: 130px; */
  position: relative;
  overflow: hidden;
  border-left: 4px solid transparent;
  border-radius: 4px;
}

.kpi-card.primary {
  border-left-color: #409EFF;
  background: linear-gradient(135deg, rgba(64,158,255,0.1) 0%, rgba(255,255,255,1) 100%);
}

.kpi-card.success {
  border-left-color: #67C23A;
  background: linear-gradient(135deg, rgba(103,194,58,0.1) 0%, rgba(255,255,255,1) 100%);
}

.kpi-card.warning {
  border-left-color: #E6A23C;
  background: linear-gradient(135deg, rgba(230,162,60,0.1) 0%, rgba(255,255,255,1) 100%);
}

.kpi-card.danger {
  border-left-color: #F56C6C;
  background: linear-gradient(135deg, rgba(245,108,108,0.1) 0%, rgba(255,255,255,1) 100%);
}

.kpi-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 40px;
  opacity: 0.3;
}

.kpi-icon .el-icon {
  font-size: 40px;
}

.kpi-content {
  /* padding: 20px; */
}

.kpi-title {
  font-size: 16px;
  color: #909399;
  margin-bottom: 10px;
}

.kpi-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.kpi-change {
  font-size: 14px;
  display: flex;
  align-items: center;
}

.kpi-change.up {
  color: #67C23A;
}

.kpi-change.down {
  color: #F56C6C;
}

/* 图表样式 */
.chart-card {
  margin-bottom: 20px;
  height: 400px;
}

.chart {
  width: 100%;
  height: 330px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.chart-controls {
  display: flex;
  align-items: center;
}

.info-icon {
  color: #909399;
  cursor: pointer;
  font-size: 18px;
}

@media screen and (max-width: 768px) {
  .kpi-section .el-col {
    margin-bottom: 15px;
  }
  
  .chart-card {
    height: auto;
  }
  
  .chart {
    height: 250px;
  }
}
</style> 